package org.distributed.transaction.core.interceptor;

import java.nio.charset.StandardCharsets;

import org.distributed.transaction.core.constants.TracingConstants;
import org.distributed.transaction.core.context.TracingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * 
 * feign请求的前置拦截器
 * 
 * @author chenfanglin
 */
public class FeignInterceptor implements RequestInterceptor {

	private static final Logger log = LoggerFactory.getLogger(SpringWebInterceptor.class);

	@Override
	public void apply(RequestTemplate template) {
		/**
		 * 传输tracing信息,放到请求头中
		 */
		if (TracingContext.tracing().hasGroup()) {
			String groupId = TracingContext.tracing().groupId();
			log.debug("tracing transmit group:{}", groupId);
			template.header(TracingConstants.HEADER_KEY_GROUP_ID, groupId);
			template.header(TracingConstants.HEADER_KEY_APP_MAP, Base64Utils
					.encodeToString(TracingContext.tracing().appMapString().getBytes(StandardCharsets.UTF_8)));
		}
	}

}
